package com.example.customannotation.customAnnotaition;

/**
 * Created with IntelliJ IDEA 2023.
 * Description:
 * User: homechen
 * Date: 2024-04-24
 * Time: 19:52
 */

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

/**
 * 使用AOP的方式实现自定义注解
 */
@Aspect
@Component
public class CustomLogAspect {
    @Around("@annotation(logAnnotation)")   // 去环绕这个注解实现
    public Object logAround(ProceedingJoinPoint joinPoint, CustomLogAnnotation logAnnotation) throws Throwable {   // 拿到当前方法和注解
        if (logAnnotation.enable()) {
            // 此时为 true 代表启用了这个注解
            System.out.println("Before method execution：" + joinPoint.getSignature().getName());   // 方法执行前处理  拿到这个方法名称
            long start = System.currentTimeMillis();
            Object result = joinPoint.proceed();  // 执行方法的结果
            long time = System.currentTimeMillis() - start;
            System.out.println("After method execution：" + time + " | " + logAnnotation.value());
            return result; // 返回结果
        } else {
            return joinPoint.proceed();
        }
    }
}
